import sys
import re
from loguru import logger
from tiny_logger import TinyLogger

class LineProcessor:
    def parse_file(self, file: str) -> list[str]:
        """解析文件
        Return: lines
        """
        try:
            with open(file, 'r') as file:
                return file.readlines()
        except FileNotFoundError:
            logger.error(f"Could not find smaps file for {file}")
            return None

    def process(self, file):
        result = []
        seg_info = self.init_seg()
        
        for line in self.parse_file(file):
            if self.skip(line):
                continue
            head = self.header(line)
            if head:
                # 如果seg_info 信息完整, 放入结果
                if self.is_valid_seg(seg_info):
                    result.append(seg_info)
                    seg_info = self.init_seg()
                self.update_seg_head(seg_info, head)
            else:
                if self.line_to_val(line):
                    
                    self.update_seg_body(seg_info, self.line_to_val(line))
        
        if self.is_valid_seg(seg_info):
            result.append(seg_info)
        return result

    def skip(self, line: str) -> bool:
        """遍历过程的过滤条件
        """
        return False

    def header(self, line):
        """Segment 的 header 可能为空
        """
        return None

    def init_seg(self):
        """segment 初始化对象
        """
        return {}

    def update_seg_head(self, seg: dict, head) -> dict:
        """如果head不为空，更新seg对象

        Args:
            seg: dict
            head: xxx
        有副作用 seg 会被修改
        """
        return seg # 同时返回修改后的seg
    
    def update_seg_body(self, seg: dict, part) -> dict:
        """如果head不为空，更新seg对象

        Args:
            seg: dict
            part: 片段中一行解析出来的信息
        有副作用 seg 会被修改
        """
        return seg

    def line_to_val(self, line: str):
        """解析一行得到的值
        """
        return None

    def is_valid_seg(self, seg: dict) -> bool:
        """seg_info 有效性检查
        """
        return len(seg) > 0 
